#include "plotdialog.h"
#include <QVBoxLayout>
#include <QMouseEvent>
#include <QDateTime>
#include <QRandomGenerator>

PlotDialog::PlotDialog(QWidget *parent)
    : QDialog(parent)
{
    customPlot = new QCustomPlot(this);
    cursorLine = new QCPItemLine(customPlot); // 创建竖向光标
    cursorLabel = new QCPItemText(customPlot); // 创建交点Y值标签
    setupPlot();
    setupCursor();

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(customPlot);
    setLayout(layout);
    setWindowTitle("趋势图");
    resize(1024, 768);
}

PlotDialog::~PlotDialog()
{
    delete customPlot;
}

QVector<QDateTime>gui_time(1);
QVector<double>myguiData(1);

void PlotDialog::setupPlot()
{
    // 生成时间序列和随机数
    QVector<double> x(1), y(1);

    // 确保 x 和 y 的大小与 gui_time 相同
    x.resize(gui_time.size());
    y.resize(gui_time.size());

    for (int i = 0; i < gui_time.size(); i++)
    {
        QDateTime dateTime = gui_time.at(i);
        // 对 dateTime 进行操作
        x[i] = gui_time[i].toMSecsSinceEpoch()/1000.0; // 时间转换为秒
        y[i] = myguiData[i];
    }

    // 创建图形
    customPlot->addGraph();
    customPlot->graph(0)->setData(x, y);

    // 计算Y轴范围
    double yMin = *std::min_element(y.constBegin(), y.constEnd());
    double yMax = *std::max_element(y.constBegin(), y.constEnd());

    customPlot->xAxis->setLabel("时间");
    customPlot->yAxis->setLabel("值");
    customPlot->xAxis->setRange(x.first(), x.last());
    // 设置Y轴范围
    customPlot->yAxis->setRange(yMin - 10, yMax + 10);

    // 设置数据点样式
    QCPScatterStyle scatterStyle;
    scatterStyle.setShape(QCPScatterStyle::ssCircle); // 设置形状为圆形
    scatterStyle.setSize(10);                        // 设置大小
    scatterStyle.setPen(QPen(Qt::blue));             // 设置边框颜色
    scatterStyle.setBrush(Qt::red);                  // 设置填充颜色
    customPlot->graph(0)->setScatterStyle(scatterStyle);

    // 设置时间轴格式
    QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
    dateTicker->setDateTimeFormat("yyyy-MM-dd\nhh:mm:ss");
    customPlot->xAxis->setTicker(dateTicker);


    // 添加数据点标签（可选）
#if 0
    for (int i = 0; i < x.size(); i++)
    {
        QCPItemText *textLabel = new QCPItemText(customPlot);
        textLabel->setPositionAlignment(Qt::AlignBottom | Qt::AlignHCenter);
        textLabel->position->setType(QCPItemPosition::ptPlotCoords);
        textLabel->position->setCoords(x[i], y[i]); // 设置标签位置
        textLabel->setText(QString::number(y[i])); // 显示数据值
        textLabel->setFont(QFont("Arial", 8));     // 设置字体
        textLabel->setColor(Qt::red);              // 设置颜色
    }
#endif

    customPlot->replot();
    // 仅启用缩放功能，禁用拖拽功能
    customPlot->setInteractions(QCP::iRangeZoom);
}

void PlotDialog::setupCursor()
{
    // 设置竖向光标
    cursorLine->start->setType(QCPItemPosition::ptPlotCoords);
    cursorLine->end->setType(QCPItemPosition::ptPlotCoords);
    cursorLine->start->setCoords(0, 0); // 初始位置
    cursorLine->end->setCoords(0, 100);
    cursorLine->setPen(QPen(Qt::red, 1, Qt::DashLine));

    // 设置交点Y值标签
    cursorLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignRight);
    cursorLabel->position->setType(QCPItemPosition::ptAxisRectRatio);
    cursorLabel->position->setCoords(0.98, 0.02); // 显示在右上角
    cursorLabel->setText("Y: -");
    cursorLabel->setColor(Qt::black);
    cursorLabel->setFont(QFont("Arial", 10));

    // 连接鼠标事件
    connect(customPlot, &QCustomPlot::mouseMove, this, &PlotDialog::onMouseMove);
    connect(customPlot, &QCustomPlot::mousePress, this, &PlotDialog::onMousePress);
    connect(customPlot, &QCustomPlot::mouseRelease, this, &PlotDialog::onMouseRelease);
}

void PlotDialog::onMouseMove(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        // 获取鼠标位置的X坐标
        double mouseX = customPlot->xAxis->pixelToCoord(event->pos().x());

        // 查找最近的数据点
        auto graphData = customPlot->graph(0)->data();
        auto nearestPoint = graphData->constEnd();
        double minDistance = std::numeric_limits<double>::max();

        for (auto it = graphData->constBegin(); it != graphData->constEnd(); ++it)
        {
            double distance = qAbs(it->key - mouseX); // 计算X坐标的距离
            if (distance < minDistance)
            {
                minDistance = distance;
                nearestPoint = it;
            }
        }

        if (nearestPoint != graphData->constEnd())
        {
            double x = nearestPoint->key; // 最近数据点的X坐标
            double y = nearestPoint->value; // 最近数据点的Y坐标

            // 更新竖向光标的位置
            double yMin = customPlot->yAxis->range().lower;
            double yMax = customPlot->yAxis->range().upper;
            cursorLine->start->setCoords(x, yMin);
            cursorLine->end->setCoords(x, yMax);

            // 将X坐标（时间戳）转换为时间
            QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(x * 1000); // 转换为毫秒
            QString timeStr = dateTime.toString("yyyy-MM-dd hh:mm:ss");

            // 更新光标标签内容
            cursorLabel->setText(QString("Time: %1\nY: %2").arg(timeStr).arg(y, 0, 'f', 2));

            // 动态调整Y轴范围
            if (y < yMin || y > yMax)
            {
                double newYMin = yMin;
                double newYMax = yMax;
                if (y < yMin) newYMin = y - 10; // 向下扩展10个单位
                if (y > yMax) newYMax = y + 10; // 向上扩展10个单位
                customPlot->yAxis->setRange(newYMin, newYMax);
            }
            // 重绘图形
            customPlot->replot();
        }
    }
}

void PlotDialog::onMousePress(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        // 开始拖动光标
        onMouseMove(event);
    }
}

void PlotDialog::onMouseRelease(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        // 结束拖动光标
        onMouseMove(event);
    }
}
